package com.hrt.web.orderInfor.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.GiftDetail;
import com.hrt.bean.OrderDetail;
import com.hrt.bean.OrderInfor;
import com.hrt.bean.OrderStatus;
import com.hrt.bean.PayType;
import com.hrt.bean.PostType;
import com.hrt.demo.wsb.record.RecordOnlineController;
import com.hrt.util.WebParams;
import com.hrt.util.upload.Plupload;
import com.hrt.util.upload.UploadUtil;
import com.hrt.vo.OrderDetailVO;
import com.hrt.vo.OrderInforVO;
import com.hrt.web.comments.service.CommentsWebService;
import com.hrt.web.member.service.HRTMemberService;
import com.hrt.web.orderInfor.service.WebOrderDetailService;
import com.hrt.web.orderInfor.service.WebOrderService;
import com.hrt.web.product.service.GiftDetailService;
@Controller
@RequestMapping("web/orderInfor")
public class WebOrderController extends BaseController<OrderInfor>{
	@Autowired
	private WebOrderService webOrderService;
	@Autowired 
	private  GiftDetailService giftDetailService;
	
	@Autowired
	private WebOrderDetailService webOrderDetailService;
	@Autowired
	private HRTMemberService hrtMemberService;
	
	
	protected Logger logger=Logger.getLogger(RecordOnlineController.class);
	
	
	
	protected String FileDir = WebParams.WEB_RECORD_UPLOAD_FOLER;
	
	protected String subfix = WebParams.WEB_RECORD_SUBFIX;

	
	
	//评论
	@Autowired
	private CommentsWebService commentsWebService;
	
	private List<Map<String, Object>> orderStatusList;
	private List<Map<String, Object>> typeList;
	private GiftDetail giftDetail;
	
	//多图片上传
	private List<File> files;

	@Autowired
	private UploadUtil uploadUtil;
	
	public static final String fileURL = "uploadfile/"; 
	
	public GiftDetail getGiftDetail() {
		return giftDetail;
	}
	public void setGiftDetail(GiftDetail giftDetail) {
		this.giftDetail = giftDetail;
	}
	public List<File> getFiles() {
		return files;
	}
	public void setFiles(List<File> files) {
		this.files = files;
	}
	 
	
	public List<Map<String, Object>> getTypeList() {
		typeList = PayType.getTypeList();
		return typeList;
	}

	public void setTypeList(List<Map<String, Object>> typeList) {
		this.typeList = typeList;
	}
	public List<Map<String, Object>> getOrderStatusList() {
		orderStatusList = OrderStatus.getOrderStatusList();
		return orderStatusList;
	}

	public void setOrderStatusList(List<Map<String, Object>> orderStatusList) {
		this.orderStatusList = orderStatusList;
	}
	/**
	 * 获取邮递类型
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "post")
	@ResponseBody
	public Map post(HttpServletRequest request) {
		Map result = new HashMap();
		
		List<PostType> postList = webOrderService.getPostType();
		result.put("postList", postList);
		return result;
		
		
	}
	/**
	 * 
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/list")
	public ModelAndView list(@RequestParam(value = "memberId",required = true) Long memberId,
			@RequestParam(value = "status",required = false) Integer status,
			HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		//根据memberId和status返回hql语句
		String hql = webOrderService.getHQLByMBRAndStatus(memberId, status);
		list = webOrderService.queryByPage(hql,getPageIndex(), getPageSize());
		this.setTotalCount(webOrderService.getOrderInforByMemberId(memberId,status));
		this.setPageCount(this.computePageCount(this.getTotalCount(),this.getPageSize()));

		page = this.getPage();
		this.orderStatusList = getOrderStatusList();
		this.typeList = getTypeList();
		view.addObject("orderStatusList", orderStatusList);
		view.addObject("typeList", typeList);
		view.addObject("STATUS", status);
		view.addObject("pageResult", page);
		view.setViewName("/HRTWEB/myOrder");
		return view;

	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "memberId",required = true) Long memberId,
			@RequestParam(value = "status",required = false) Integer status,
			HttpServletRequest request) {
		Map resultMap = new HashMap();
		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);
		List<OrderInfor> resultList = null;
		//根据memberId和status返回hql语句
		String hql = webOrderService.getHQLByMBRAndStatus(memberId, status);
		resultList = webOrderService.queryByPage(hql,getPageIndex(), getPageSize());
		
		this.setTotalCount(webOrderService.getOrderInforByMemberId(memberId,status));
		
		for(int i=0;i<resultList.size();i++){
			//转换时间的格式
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String createOrderTime = sdf.format(resultList.get(i).getCreateTime());
			resultList.get(i).setCreateOrderTime(createOrderTime);
		}
		setList(resultList);
		for(OrderInfor order:resultList){
			if(order!=null){
				List<OrderDetail> details = webOrderDetailService.getOrderDetailByOrderId(order.getId());
				order.setOrderDetail(details);
				//礼品规格
				for(OrderDetail oDetail:details){
					if(oDetail != null){
						oDetail.setGiftDescr(oDetail.getGiftDetail().getGiftInfor().getDescription());
					}
				}
			}
		}
		
		this.setPageCount(this.computePageCount(this.getTotalCount(),this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}
	@RequestMapping(value = "/queryByOrderId")
	public ModelAndView queryByOrderId(@RequestParam(value = "orderId",required = true) Long orderId,
			HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		List<OrderDetail> details = webOrderDetailService.getOrderDetailByOrderId(orderId);
		view.addObject("detailList", details);
		view.setViewName("/HRTWEB/myOrderDetail");
		return view;

	}
	
	/**
	 * 跳到评论页面之前
	 * */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value = "/commentByOrderId")
	public ModelAndView commentByOrderId(@RequestParam(value = "orderId",required = true) Long orderId,HttpServletRequest request) {
		ModelAndView view = new ModelAndView();
		List<GiftDetail> giftDetails = new ArrayList<GiftDetail>();
		List<OrderDetail> orderDetails = webOrderDetailService.getOrderDetailByOrderId(orderId);
		//用来拼接礼品规格id的字符串
		String gdeIds="";
		//用来判断订单有多少订单详情的数量
		int num = orderDetails.size();
		for(int i= 0; i<orderDetails.size(); i++){
			OrderDetail orderDetail = orderDetails.get(i);
			GiftDetail giftDetail = giftDetailService.getById(orderDetail.getGiftDetailId());
			giftDetail.setOrderDetailId(orderDetail.getId());
			gdeIds = gdeIds+orderDetail.getGiftDetailId()+",";
			giftDetails.add(giftDetail);
		}
		if(gdeIds != null){
			gdeIds=gdeIds.substring(0,gdeIds.length()-1);
		}

		//全部评论
//		setTotalCount((long)1);
		List  resultList= new ArrayList();
		if(gdeIds==null || gdeIds==""){
			throw new RuntimeException("礼品规格id有误");
		}else{
			List<Long> gdeIdsList = commentsWebService.findCommIdByGdeId(gdeIds);
			String gdeIdstr = "";
			if(gdeIdsList!=null && gdeIdsList.size()>0){
				for(Long sonId : gdeIdsList ){
					gdeIdstr = gdeIdstr+sonId+",";
				}
				if(gdeIdstr != ""){
					gdeIdstr=gdeIdstr.substring(0,gdeIdstr.length()-1);
				}
				
				resultList = commentsWebService.queryById(gdeIdstr, this.getPageIndex(),
						this.getPageSize(),"1");
				
				setTotalCount(commentsWebService.findNumByGdeId(gdeIdstr));
			}
		}
		this.setList(resultList);
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));
//		System.out.println("2=="+this.getTotalCount()+","+this.getPageSize());
		page = this.getPage();
		view.addObject("gdeIds", gdeIds);
		view.addObject("pageResult", page);
		//---------------全部评论结束-----------
		view.addObject("commGiftDetails", giftDetails);
		view.addObject("num", num);
		view.setViewName("/HRTWEB/commentPage/commentPage");
		return view;
		
	}
	/**
	 * 保存订单
	 * @param orderInforVO
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public ModelAndView save(@ModelAttribute("webOrderInfo") OrderInforVO orderInforVO,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		System.out.println("save");
		System.out.println("orderInforVO----------"+orderInforVO.getSummery());
		System.out.println("orderInforVO:" + orderInforVO.getPostCode());
		orderInforVO.setIsdelete(0);
		orderInforVO.setStatus(0);
		orderInforVO.setOrderSource(1);
		orderInforVO.setSender("何人堂");
		orderInforVO.setCreateTime(this.webOrderService.getDate());
		List<OrderDetailVO> details = new ArrayList<OrderDetailVO>();  
			
				
				for(OrderDetailVO od:orderInforVO.getDetails()){
					od.setIsdelete(0);
					od.setCreateTime(this.webOrderService.getDate()
							);
					
					/*od.setCreator(this.getOnlineManager(request, response)
							.getLoginName());
					od.setEditor((this.getOnlineManager(request, response)
							.getLoginName()));*/
					od.setEditTime(this.webOrderService.getDate());
					details.add(od);
				}
				webOrderService.saveOrderInfor(orderInforVO, details);
			
			view.setViewName("/HRTWEB/order_success");
			return view;
	}
	/**
	 * 保存订单
	 * @param orderInfor
	 * @param giftDetailId
	 * @param request
	 * @param response
	 * @return
	 *//*
	@RequestMapping(value = "/save",method = RequestMethod.POST)
	public ModelAndView save(@ModelAttribute("webOrderInfo") OrderInfor orderInfor,
			@RequestParam(value = "giftDetailId", required = true) Long giftDetailId,
			HttpServletRequest request,HttpServletResponse response){
			ModelAndView view = new ModelAndView();
			HRTMember member = hrtMemberService.getMemberByid(orderInfor.getMemberId());
			//订单基本信息
			orderInfor.setHrtMember(member);
			orderInfor.setOrderSource(0);
			orderInfor.setSender("何人堂");
			orderInfor.setCreateTime(this.webOrderService.getDate());
			//订单详细信息
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setCreateTime(this.webOrderDetailService.getDate());
			orderDetail.setCreator(member.getMbrName());
			orderDetail.setEditor(member.getMbrName());
			orderDetail.setEditTime(this.webOrderDetailService.getDate());
			
			GiftDetail giftDetail = giftDetailService.getGiftDetailById(giftDetailId);
			orderDetail.setGiftDetail(giftDetail);
		try {
			webOrderService.saveOrder(orderInfor);
			orderDetail.setOrderInfor(orderInfor);
			webOrderDetailService.saveOrderDetail(orderDetail);
			
		} catch (Exception 	e) {
			e.printStackTrace();
		}
		view.setViewName("/HRTWEB/order_success");
		return view;
		
	}*/
	/**
	 * 删除订单
	 * @param orderId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public String delete(@RequestParam(value = "orderId",required = true) Long orderId,
			HttpServletRequest request,HttpServletResponse response) {
		OrderInfor orderInfor = webOrderService.getOrderByid(orderId);
		orderInfor.setIsView(new Integer(1));
		webOrderService.updateOrder(orderInfor);
		return "success";
	}
	/**
	 * 恢复订单
	 * @param orderId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/recovery")
	@ResponseBody
	public String recovery(@RequestParam(value = "orderId",required = true) Long orderId,
			HttpServletRequest request,HttpServletResponse response) {
		OrderInfor orderInfor = webOrderService.getOrderByid(orderId);
		orderInfor.setIsView(new Integer(0));
		webOrderService.updateOrder(orderInfor);
		return "success";
	}
	/**
	 * 彻底删除订单
	 * @param orderId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/destory")
	@ResponseBody
	public String destory(@RequestParam(value = "orderId",required = true) Long orderId,
			HttpServletRequest request,HttpServletResponse response) {
		OrderInfor orderInfor = webOrderService.getOrderByid(orderId);
		orderInfor.setIsView(new Integer(2));
		webOrderService.updateOrder(orderInfor);
		return "success";
	}
	
	
	
	//图片上传
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void upload(Plupload plupload,HttpServletRequest request, HttpServletResponse response) {
		plupload.setRequest(request);  
        //文件存储路径  
        File dir = new File(plupload.getRequest().getSession().getServletContext().getRealPath("/") + fileURL);  
        try {  
            //上传文件  
        	File file = uploadUtil.upload(plupload, dir);  
            //判断文件是否上传成功（被分成块的文件是否全部上传完成）  
        	if (file != null) {
        		//获取上传的图片名称
        		//全路径
        		 String UPLOAD_SUCCESS = WebParams.DO_MAIN + request.getContextPath() + "/" + fileURL + file.getName();
        		System.out.println("sdjshd===>"+UPLOAD_SUCCESS);
        		byte[] responseBytes = UPLOAD_SUCCESS.getBytes();
 				response.setContentLength(responseBytes.length);
 				ServletOutputStream pw = response.getOutputStream();
 				pw.write(responseBytes);
 				pw.flush();
 				pw.close();
            }else{
            	String UPLOAD_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";
            	response.setContentType("application/json");
				final byte[] responseBytes = UPLOAD_ERROR.getBytes();
				response.setContentLength(responseBytes.length);
				ServletOutputStream pw = response.getOutputStream();
				pw.write(responseBytes);
				pw.flush();
				pw.close();
//            	return "fail";
            }
    		
        } catch (IllegalStateException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
//        return "success";  
    }  
	/**
	 * 在线录音文件上传
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/uploadVoice", method = RequestMethod.POST)
	@ResponseBody 
	public String uploadVoice(HttpServletRequest request,
			HttpServletResponse response) {
		
		/**
		 * 获取项目主路径
		 */
		 String basePath=request.getSession().getServletContext().getRealPath("/");
		 
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		// plupload.setRequest(multipartRequest);
		 //Plupload plupload,
		 Map<String, MultipartFile> map=multipartRequest.getFileMap();
		 System.err.println("hello world"+map.size());
		 
		 File folder=new File(basePath+"/"+FileDir);
			if(!folder.exists()){
				folder.mkdirs();
				folder.setReadable(true);
				folder.setWritable(true);
				folder.setExecutable(true);
			}
			System.out.println(folder.getAbsolutePath());
			String targetFileName="rec_"+System.currentTimeMillis()+subfix;
			File file=new File(folder.getPath()+"/"+targetFileName);
			if(!file.exists()){
				try {
					file.createNewFile();
					file.setReadable(true);
					file.setWritable(true);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.error(e.getStackTrace());
					return "fail";
				}
			}
			
		 if(map!=null && !map.isEmpty()){
			 for(Iterator<MultipartFile> itr=map.values().iterator();itr.hasNext();){
				 MultipartFile recFile= itr.next();
				 try {
					 FileOutputStream ous=new FileOutputStream(file);
					InputStream ins=recFile.getInputStream();
					byte[] b=recFile.getBytes();
					
						ous.write(b);

					ous.flush();
					ous.close();
					ins.close();
					//文件上传的相对路径
					String url = WebParams.WEB_RECORD_UPLOAD_FOLER+targetFileName;
					logger.info("录音文件生成成功："+file.getAbsolutePath());
					logger.info("录音文件生成成功："+file.getCanonicalPath());
					logger.info("录音文件生成成功："+file.getPath());
					return "{\"saved\": 1,\"file\": "+file.getCanonicalPath()+"}";
				} catch (IOException e) {
					// TODO Auto-generated catch block
					logger.error(e.getStackTrace());
					return "fail";
				}
			 }
		 }
		
		
	          
	        return "fail";
		
	}
	
	
	
}
